package com.example.webdemo.controller;

import com.example.webdemo.common.ApiResult;
import com.example.webdemo.common.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * @author zp
 * @version 1.0
 * @description: 全局异常处理
 * @date 2023/7/25 18:55
 */
@Slf4j
@RestControllerAdvice
public class ErrorController {
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ApiResult handleMethodArgumentNotValidException(Exception exception) {
        StringBuilder errorInfo = new StringBuilder();
        BindingResult bindingResult=null;
        if(exception instanceof MethodArgumentNotValidException){
            bindingResult= ((MethodArgumentNotValidException)exception).getBindingResult();
        }
        if(exception instanceof BindException){
            bindingResult= ((BindException)exception).getBindingResult();
        }
        for(int i = 0; i < Objects.requireNonNull(bindingResult).getFieldErrors().size(); i++){
            if(i > 0){
                errorInfo.append(",");
            }
            FieldError fieldError = bindingResult.getFieldErrors().get(i);
            errorInfo.append(fieldError.getField()).append(" :").append(fieldError.getDefaultMessage());
        }
        log.error(errorInfo.toString());
        //这里返回自己的Result的结果类。
        return ApiResult.fail(errorInfo.toString());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ApiResult handleDefaultException(Exception exception) {
        log.error(exception.toString());
        //这里返回自己的Result的结果类。
        return ApiResult.fail(ResultCodeEnum.SYSTEM_ERROR);
    }
}
